package cn.com.chec.en.controller.admin;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import cn.com.chec.en.dao.ChannelInfoDao;
import cn.com.chec.en.dao.LanguageInfoDao;
import cn.com.chec.en.dao.LogInfoDao;
import cn.com.chec.en.model.domain.ChannelInfo;
import cn.com.chec.en.model.domain.LanguageInfo;
import cn.com.chec.en.model.domain.UserInfo;
import cn.com.chec.en.util.FileUtils;
import cn.com.chec.en.util.PageBean;

@Controller
@RequestMapping({ "/admin/channel" })
public class ChannelInfoAdminController {
	protected static final Logger logger = Logger
			.getLogger(ChannelInfoAdminController.class);

	@Resource
	private LogInfoDao logInfoDao;

	@Resource
	private ChannelInfoDao channelInfoDao;

	@Resource
	private LanguageInfoDao languageInfoDao;

	@Resource
	private List<String> allowedUploadImages;

	@RequestMapping({ "/showInsert" })
	public ModelAndView showInsert(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws Exception {
		ModelAndView mav = new ModelAndView(
				"admin/channelInfo/channelInfoInsert");
		int languageId = StringUtils.isNotBlank(request
				.getParameter("languageId")) ? Integer.parseInt(request
				.getParameter("languageId")) : 1;
		int channelParentId = StringUtils.isNotBlank(request
				.getParameter("channelParentId")) ? Integer.parseInt(request
				.getParameter("channelParentId")) : 0;
		List<LanguageInfo> languageInfoList = this.languageInfoDao.getAll();
		List<ChannelInfo> channelInfoList = this.channelInfoDao
				.getSubListByParentIdLanguageId(languageId, channelParentId, 0,
						2147483647);
		Map<Integer, String> channelInfoMap = this.channelInfoDao.getAllChannelAsMap();
		map.put("languageInfoList", languageInfoList);
		map.put("channelInfoList", channelInfoList);
		map.put("channelInfoMap", channelInfoMap);
		map.put("languageId", Integer.valueOf(languageId));
		map.put("channelParentId", Integer.valueOf(channelParentId));
		map.put("act", "insert");
		mav.addAllObjects(map);
		return mav;
	}

	@SuppressWarnings("deprecation")
	@RequestMapping({ "/insert" })
	public ModelAndView insert(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		ModelAndView mav = new ModelAndView("admin/common/message");
		String message = "";
		int languageId = StringUtils.isNotBlank(request
				.getParameter("languageId")) ? Integer.parseInt(request
				.getParameter("languageId")) : 1;
		int channelParentId = StringUtils.isNotBlank(request
				.getParameter("channelParentId")) ? Integer.parseInt(request
				.getParameter("channelParentId")) : 0;
		String channelName = request.getParameter("channelName");
		String channelDesc = request.getParameter("channelDesc");
		int showType = StringUtils.isNotBlank(request.getParameter("showType")) ? Integer
				.parseInt(request.getParameter("showType")) : 0;

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest.getFile("channelImage");
		String originalFilename = multipartFile.getOriginalFilename();
		if ((StringUtils.isNotBlank(originalFilename))
				&& (!isAllowed(originalFilename))) {
			map.put("message", "上传文件类型不符合,必须是以下几种<br/>"
					+ this.allowedUploadImages.toString());
			return new ModelAndView("admin/common/message", map);
		}

		String fileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")
				+ "." + FilenameUtils.getExtension(originalFilename);
		String basePath = request.getRealPath("/") + "/";
		String relativePath = "userfiles/upload/images/"
				+ DateFormatUtils.format(new Date(), "yyyy-MM-dd").replaceAll(
						"-", "/") + "/";
		FileUtils.mkdirs(basePath + relativePath);
		multipartFile.transferTo(new File(basePath + relativePath + fileName));

		ChannelInfo info = new ChannelInfo();
		info.setLanguageId(languageId);
		info.setChannelParentId(channelParentId);
		info.setChannelName(channelName);
		info.setChannelDesc(channelDesc);
		info.setShowType(showType);
		info.setChannelImage(relativePath + fileName);
		if (this.channelInfoDao.insert(info)) {
			message = "添加频道成功!";
			UserInfo userInfoSession = (UserInfo) session
					.getAttribute("systemUserInfo");
			this.logInfoDao.log(userInfoSession.getId(), 1, channelParentId,
					"新增栏目 : " + channelName);
		} else {
			message = "添加频道失败!";
		}
		map.put("message", message);
		mav.addAllObjects(map);
		return mav;
	}

	@RequestMapping({ "/showUpdate" })
	public ModelAndView showUpdate(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws Exception {
		ModelAndView mav = new ModelAndView("admin/channelInfo/channelInfoEdit");
		List<LanguageInfo> languageInfoList = this.languageInfoDao.getAll();
		int channelId = StringUtils.isNotBlank(request
				.getParameter("channelId")) ? Integer.valueOf(
				request.getParameter("channelId")).intValue() : 0;
		ChannelInfo channelInfo = this.channelInfoDao
				.getChannelByChannelId(channelId);

		List<ChannelInfo> channelInfoList = this.channelInfoDao
				.getSubListByParentIdLanguageId(
						channelInfo.getLanguageId(),
						this.channelInfoDao.getChannelByChannelId(
								channelInfo.getChannelParentId())
								.getChannelParentId(), 0, 2147483647);

		map.put("channelInfoList", channelInfoList);
		map.put("languageInfoList", languageInfoList);
		map.put("channelInfo", channelInfo);
		map.put("act", "update");
		mav.addAllObjects(map);
		return mav;
	}

	@SuppressWarnings("deprecation")
	@RequestMapping({ "/update" })
	public ModelAndView update(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		ModelAndView mav = new ModelAndView("admin/common/message");
		String message = "";
		int channelId = StringUtils.isNotBlank(request
				.getParameter("channelId")) ? Integer.parseInt(request
				.getParameter("channelId")) : 0;
		String channelName = request.getParameter("channelName");
		String channelDesc = request.getParameter("channelDesc");

		ChannelInfo channelInfo = this.channelInfoDao
				.getChannelByChannelId(channelId);
		channelInfo.setChannelName(channelName);
		channelInfo.setChannelDesc(channelDesc);

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest.getFile("channelImage");
		String originalFilename = multipartFile.getOriginalFilename();
		if (StringUtils.isNotBlank(originalFilename)) {
			if (!isAllowed(originalFilename)) {
				map.put("message", "上传文件类型不符合,必须是以下几种<br/>"
						+ this.allowedUploadImages.toString());
				return new ModelAndView("admin/common/message", map);
			}
			String fileName = DateFormatUtils.format(new Date(),
					"yyyyMMddHHmmss")
					+ "."
					+ FilenameUtils.getExtension(originalFilename);
			String basePath = request.getRealPath("/") + "/";
			String relativePath = "userfiles/upload/images/"
					+ DateFormatUtils.format(new Date(), "yyyy-MM-dd")
							.replaceAll("-", "/") + "/";
			FileUtils.mkdirs(basePath + relativePath);
			multipartFile.transferTo(new File(basePath + relativePath
					+ fileName));
			channelInfo.setChannelImage(relativePath + fileName);
		}
		if (this.channelInfoDao.update(channelInfo)) {
			message = "更新频道成功!";
			UserInfo userInfoSession = (UserInfo) session
					.getAttribute("systemUserInfo");
			this.logInfoDao.log(userInfoSession.getId(), 3, channelId,
					"修改栏目 : " + channelName);
		} else {
			message = "更新频道失败!";
		}
		map.put("message", message);
		mav.addAllObjects(map);
		return mav;
	}

	@RequestMapping({ "/list" })
	public ModelAndView list(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws Exception {
		ModelAndView mav = new ModelAndView("admin/channelInfo/channelInfoList");

		List<LanguageInfo> languageInfoList = this.languageInfoDao.getAll();
		Map<Integer, String> languageMap = this.languageInfoDao.getLanuageMap();

		int languageId = StringUtils.isNotBlank(request
				.getParameter("languageId")) ? Integer.parseInt(request
				.getParameter("languageId")) : 1;
		int channelParentId = StringUtils.isNotBlank(request
				.getParameter("channelParentId")) ? Integer.parseInt(request
				.getParameter("channelParentId")) : 0;
		int curPage = StringUtils.isNotBlank(request.getParameter("curPage")) ? Integer
				.parseInt(request.getParameter("curPage")) : 1;
		PageBean pageBean = new PageBean();
		pageBean.setCurPage(curPage);
		List<ChannelInfo> channelInfoList = this.channelInfoDao
				.getSubListByParentIdLanguageId(languageId, channelParentId,
						pageBean.getStart(), pageBean.getRowsPerPage());
		pageBean.setMaxRowCount(this.channelInfoDao
				.getCountByParentIdLanguageId(languageId, channelParentId));
		pageBean.setMaxPage();
		pageBean.setPageNoList();
		ChannelInfo clObj = null;
		if (channelParentId > 0) {
			clObj = this.channelInfoDao.getChannelByChannelId(channelParentId);
		}

		map.put("languageInfoList", languageInfoList);
		map.put("languageMap", languageMap);
		map.put("channelInfoList", channelInfoList);
		map.put("clObj", clObj);
		map.put("channelParentId", Integer.valueOf(channelParentId));
		map.put("languageId", Integer.valueOf(languageId));
		map.put("pageBean", pageBean);
		mav.addAllObjects(map);
		return mav;
	}

	@RequestMapping({ "/sort" })
	public ModelAndView sort(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws Exception {
		ModelAndView mav = new ModelAndView("admin/common/message");
		String message = "";
		String[] checkIds = request.getParameter("checkId").split(",");
		if (this.channelInfoDao.sort(checkIds))
			message = "栏目排序成功!";
		else {
			message = "栏目排序失败!";
		}
		map.put("message", message);
		mav.addAllObjects(map);
		return mav;
	}

	@RequestMapping({ "/delete" })
	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ModelMap map)
			throws Exception {
		ModelAndView mav = new ModelAndView("admin/common/message");
		String message = "";
		int channelId = StringUtils.isNotBlank(request
				.getParameter("channelId")) ? Integer.valueOf(
				request.getParameter("channelId")).intValue() : 0;
		String channelname = new ChannelInfoDao().getChannelByChannelId(
				channelId).getChannelName();

		if (this.channelInfoDao.delete(channelId)) {
			message = "栏目删除成功!";
			UserInfo userInfoSession = (UserInfo) session
					.getAttribute("systemUserInfo");
			this.logInfoDao.log(userInfoSession.getId(), 2, channelId,
					"删除栏目 : " + channelname);
		} else {
			message = "栏目删除失败!";
		}
		map.put("message", message);
		mav.addAllObjects(map);
		return mav;
	}

	public boolean isAllowed(String fileName) {
		for (String suffix : this.allowedUploadImages) {
			if (StringUtils.equalsIgnoreCase(suffix,
					FilenameUtils.getExtension(fileName))) {
				return true;
			}
		}
		return false;
	}
}